// 全局配置
const API = {
    productList: '/system/product/client/list',
    categoryList: '/system/category/list',
    setmealList: '/system/setmeal/list',
    getMyOrderList: '/user/getMyOrderList'
};

// 初始化加载
document.addEventListener('DOMContentLoaded', () => {
    loadCategories();
    loadProducts();
    loadSetmeals();
    initCarousel();
    bindEvents();
});

// 加载分类
async function loadCategories() {
    try {
        const data = await fetchData(API.categoryList);
        renderCategories(data.rows);
    } catch (error) {
        console.error('分类加载失败:', error);
    }
}

// 加载商品
async function loadProducts(params = {}) {
    try {
        const data = await fetchListData(API.productList, params);
        console.log('商品加载成功:', data);
        renderProducts(data.data);
    } catch (error) {
        console.error('商品加载失败:', error);
    }
}


// 新增套餐加载方法
async function loadSetmeals() {
    try {
        const data = await fetchData(API.setmealList);
        renderSetmeals(data.rows.filter(s => s.status === 0)); // 只显示启用状态的套餐
    } catch (error) {
        console.error('套餐加载失败:', error);
    }
}


// 渲染分类
function renderCategories(categories) {
    const container = document.querySelector('.category-grid');
    container.innerHTML = `
        <div class="category-card active" data-category="" onclick="filterByCategory('')">全部</div>
        ${categories.map(cat => `
            <div class="category-card" 
                 data-category="${cat.id}" 
                 onclick="filterByCategory('${cat.id}')">
                ${cat.name}
            </div>
        `).join('')}
    `;
}

// 渲染商品
function renderProducts(products) {
    const container = document.querySelector('.product-grid');
    container.innerHTML = products
        .map(p => `
            <div class="product-card">
                <div class="product-image">
                    <img src="${p.imgUrl || '/images/banners/1.png'}" 
                         alt="${p.productName}"
                         onerror="this.src='/images/banners/1.png'">
                </div>
                <div class="product-info">
                    <div class="product-title">${p.productName}</div>
                    <div class="product-price">¥ ${p.productPrice.toFixed(2)}</div>
                    <button class="add-to-cart" onclick="addToCart({
                    type: 'product',
                    id: '${p.id}',
                    name: '${p.productName}',
                    price: ${p.productPrice},
                    imgUrl: '${p.imgUrl}',
                    quantity: 1})">加入购物车</button>
                </div>
            </div>
        `).join('');
}

// 新增套餐渲染方法
function renderSetmeals(setmeals) {
    const container = document.querySelector('.setmeal-grid');
    container.innerHTML = setmeals.map(s => `
        <div class="setmeal-card">
            <div class="setmeal-image">
                <span class="setmeal-badge">送 ${s.socre}积分</span>
                <img src="${s.imgUrl || '/images/banners/1.png'}" 
                     alt="${s.setmealName}"
                     onerror="this.src='/images/banners/1.png'; this.onerror = null;">
            </div>
            <div class="setmeal-info">
                <div class="setmeal-name">${s.setmealName}</div>
                <div class="setmeal-price">¥ ${s.setmealPrice.toFixed(2)}</div>
                <div class="setmeal-score">已售 ${Math.floor(Math.random()*500 + 100)}份</div>
                <button class="add-to-cart" 
        onclick="addToCart({
            type: 'setmeal',
            id: '${s.id}',
            name: '${s.setmealName}',
            price: ${s.setmealPrice},
            imgUrl: '${s.imgUrl}',
            quantity: 1
        })">立即购买</button>
            </div>
        </div>
    `).join('');
}

// 分类筛选
function filterByCategory(categoryId) {
    document.querySelectorAll('.category-card').forEach(el => {
        el.classList.toggle('active', el.dataset.category === categoryId);
    });
    loadProducts({ categoryId });
}

// 搜索功能
let searchTimer;
document.querySelector('.search-input').addEventListener('input', (e) => {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => {
        loadProducts({ productName: e.target.value });
    }, 500);
});

// 轮播图逻辑
let currentSlide = 0;
function initCarousel() {
    const slides = document.querySelectorAll('.slide');
    setInterval(() => {
        slides[currentSlide].classList.remove('active');
        currentSlide = (currentSlide + 1) % slides.length;
        slides[currentSlide].classList.add('active');
    }, 5000);
}

// 事件绑定
function bindEvents() {
    document.querySelectorAll('.add-to-cart').forEach(btn => {
        btn.addEventListener('click', () => {
            alert('已加入购物车！');
        });
    });
}

// 通用请求方法
async function fetchData(url, params = {}) {
    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify(params)
    });
    if (!response.ok) throw new Error('请求失败');
    return response.json();
}

async function fetchListData(url, params = {}) {
    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify(params)
    });
    console.log('请求响应:', response);
    if (!response.ok) throw new Error('请求失败');
    return response.json();
}